// pages/games/scratchTicket/index.js
import Scratch from "./scratch.js"
const phoneReg = /^1[3-9]\d{9}$|^([1|2|3|4|5|6|7|8|9])\d{7}$|^[0][9]\d{8}$|^[6]([8|6])\d{5}$/
let scratch = null
const {
  GamesModel
} = require('../../../utils/games-model.js');
const gameModel = new GamesModel()
const {
  MemberModel
} = require('../../../utils/member-model.js');
const memberModel = new MemberModel();
const app = getApp()
// import Scratch from "./test.js"
Page({
  /**
   * 页面的初始数据
   */
  data: {
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    radarImg: null,
    istrue: false,
    dialogText: '',
    succeedDialog: false,
    disabled: false,
    ratio: 0, // 屏幕比例
    canvasViewIndex: 1,
    canvasClear: false, // 画布是否清楚完成
    detailData: null, // 详情数据
    canvasFlang: false,
    memberId: null, // 会员id
    gift: {}, // 奖品信息
    start: false, // 是否可以开始清除
    gameConfigName: '', // 游戏名，
    activityType: '', // 游戏类型
    activityId: '', // 游戏id
    authShow: false, // 显示授权
    login: false,
  },
  tapName: function () {
    // console.log('点击')
  },
  // 监听滚动
  handleShareHeid: function () {
    this.setData({
      radarImg: ''
    })
  },
  // 开始挂
  canvasTouch: function () {

    // 登录后直接挂
    this.getGameLottery(this.data.memberId)
  },
  // 是否登录
  isLogin: function () {
    // 如果没有登录调用登录组件
    if (!app.globalData.isLogin) {
      this.canvasToTempFilePath()
      this.setData({
        authShow: true
      })
    }
  },
  // 是否有会员id
  isMemberId: function () {
    // 没有会员ID调接口获取
    if (app.globalData.isLogin) {
      if (!this.data.memberId) {
        this.getUserInfo()
      }
    }

  },
  // 在玩一次
  handleAgain: function () {
    this.setData({
      istrue: null,
      canvasFlang: false,
      radarImg: false,
      gift: {},
      canvasClear: false
    })
    scratch = null
    scratch = new Scratch(this, {
      canvasId: 'canvasLock',
      width: 300 * this.data.ratio,
      height: 175 * this.data.ratio,
      //maskColor:'#dddddd',
      //size:15,
      //scale:1,
      scale: .9,
    })
    // setTimeout(() => {
    //   scratch = null
    //   scratch = new Scratch(this, {
    //     canvasId: 'canvasLock',
    //     width: 300 * this.data.ratio,
    //     height: 175 * this.data.ratio,
    //     //maskColor:'#dddddd',
    //     //size:15,
    //     //scale:1,
    //     scale: .9,
    //   })
    // }, 100)

    // this.showModal()
  },

  clearCanvas: function (data) {
    this.setData({
      canvasViewIndex: 101,
      canvasClear: true,
      // canvasFlang: false,
      radarImg: false
    })
    // setTimeout(
    //   this.ctx.clearRect(0, 0, this.width, this.height);
    //   this.ctx.draw();
    scratch.ctx.clearRect(0, 0, this.width, this.height);
    scratch.ctx.draw();
    if (typeof data === 'string') {
      scratch.drawErr(data)
    } else {
      if (data.activityGiftName) {
        let giftName = ''
        switch (Number(data.giftType)) {
          case 0:
          case 1:
          case 2:
            giftName = data.giftName
            break;
          case 3:
            giftName = `${data.giftAmount}积分`
            break;
          case 4:
            giftName = data.activityGiftName
            break;
          default:
            break;
        }
        scratch.drawPrize(data.activityGiftName === giftName ? '' : data.activityGiftName, giftName)
      } else {
        scratch.drawNoPrize(data.reminder)
      }
    }


  },
  // 没有活动
  // noActive: function() {
  //   this.setData({
  //     radarImg: true,
  //     istrue: true,
  //     dialogText: '暂无此类型活动'
  //   })

  // },
  succeedDialogClose: function () {
    this.setData({
      succeedDialog: false,
      radarImg: null

    })
  },
  // 调用验证接口
  // verify: function() {
  //   const that = this;
  //   const merchantId = wx.getStorageSync('merchantId')
  //   // needStatus, hideLoading, noRefetch
  //   gameModel.gameVerify({
  //     "merchantId": merchantId,
  //     "memberId": this.data.memberId,
  //     "refActivityId": (this.data.detailData && this.data.detailData.activityId) || ''
  //   }).then(data => {
  //     that.setData({
  //       canvasFlang: true,
  //       radarImg: null,
  //     })
  //     setTimeout(()=> {
  //       scratch = null
  //       scratch = new Scratch(this, {
  //         canvasId: 'canvasLock',
  //         width: 300 * this.data.ratio,
  //         height: 175 * this.data.ratio,
  //         scale: .9,
  //       })
  //     }, 100)
  //   }).catch(err => {
  //     that.setData({
  //       dialogText: err.error
  //     })
  //   })
  // },
  // 获取缩放比例
  getRatio: function () {
    let that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          ratio: res.windowWidth / 375
        })
        // w = res.windowWidth/375;
      },
    })
  },
  binderror: function () {
    console.log('canvas报错')
  },
  // 显示遮罩层
  showModal: function () {
    // 如果已经登录但是没有会员id
    if (app.globalData.isLogin && this.data.memberId == '') {
      memberModel.userInfo({
        merchantId: wx.getStorageSync('merchantId')
      }, false, true).then(data => {
        this.setData({
          memberId: data.memberId,
          login: true
        })
        setTimeout(() => {
          wx.navigateTo({
            url: `/pages/games/winningRecord/index?refActivityId=${this.data.activityType}&memberId=${this.data.memberId}`,
          })
        }, 50)

      })
    } else {
      wx.navigateTo({
        url: `/pages/games/winningRecord/index?refActivityId=${this.data.activityType}&memberId=${this.data.memberId}`,
      })
    }
  },
  // 有弹层控制canvas
  canvasToTempFilePath: function () {
    // 绘制图片
    var that = this;
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 300 * this.data.ratio,
      height: 175 * this.data.ratio,
      canvasId: 'canvasLock',
      success: function (res) {
        console.log(res.tempFilePath)
        that.setData({
          radarImg: res.tempFilePath
        });
      }
    });
  },
  // 获取游戏详情
  getGangeDetai: function () {
    const merchantId = wx.getStorageSync('merchantId')

    // '40ed3fb4-6b8a-4606-9cb3-a1e8bba5584b' ||
    gameModel.gameDetail({
      merchantId: merchantId,
      activityType: this.data.activityType,
      // activityStatus: 1,
      activityId: this.data.activityId
      // activityName: this.data.gameConfigName
    }, false, true).then(data => {
      // console.log('暂无此类型活动',data)
      if (data === null) {
        wx.showToast({
          title: `${'暂无此类型活动'}`,
          icon: 'none',
          duration: 2000
        })
        return null;
      }
      if (data.activityStatus == 0) {
        wx.showToast({
          title: `${'活动未开始'}`,
          icon: 'none',
          duration: 2000
        })
      } else if (data.activityStatus == 2) {
        wx.showToast({
          title: `${'活动已结束'}`,
          icon: 'none',
          duration: 2000
        })
      }
      // data.activityRule = (data.activityRule || '').split('\n')
      this.setData({
        detailData: data,
        gameConfigId: (data || {}).activityId
      })
      // 能获取游戏详情的时候校验是否可以刮
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   *微信会员信息
   */
  getUserInfo: function (flag) {
    const _this = this;
    memberModel.userInfo({
      merchantId: wx.getStorageSync('merchantId')
    }).then(data => {
      _this.setData({
        memberId: data.memberId,
        login: true
      })
      if (!flag) {
        // debugger
        // _this.getGameLottery(data.memberId)
      }
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 游戏抽奖
  getGameLottery: function (memberId) {
    const merchantId = wx.getStorageSync('merchantId')
    const that = this
    gameModel.gameLottery({
        "merchantId": merchantId,
        "memberId": memberId,
        "refActivityId": (this.data.detailData && this.data.detailData.activityId) || ''

      }, false, true).then(data => {
        console.log(data)
        this.setData({
          gift: data,
          start: true
        })
        // ata.activityGiftName, data.giftName
        this.clearCanvas(data)

      })
      .catch(err => {
        this.clearCanvas(err.error)
        // wx.showToast({
        //   title: `${err.error}`,
        //   icon: 'none',
        //   duration: 2000
        // })
      })
  },
  // 授权成功的回调
  loginSucceed: function () {
    // this.getGangeDetai()
    this.setData({
      radarImg: null,
      login: true
    })
    this.getUserInfo(true)
  },
  // 登录取消
  loginCancel: function () {
    this.setData({
      radarImg: null
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log('游戏', +new Date())
    // debugger
    // console.log(options)
    this.setData({
      activityType: options.activityType,
      gameConfigName: options.gameConfigName,
      activityId: options.id
    })
    // 获取游戏详情
    if (wx.getStorageSync('merchantId')) {
      this.getGangeDetai()
    } else {
      app.getInfo().then(data => {
        this.getGangeDetai()
        // debugger
        // console.log('getInfo')
      })
    }
    // 如果已经登录获取用户信息
    if (app.globalData.isLogin) {
      // debugger
      this.getUserInfo(true)
      this.setData({
        login: true
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // console.log('onReady')
    this.getRatio()
    console.log(this.data.ratio)
    //初始化刮奖界面 ，重置刮奖层状态
    scratch = new Scratch(this, {
      canvasId: 'canvasLock',
      width: 300 * this.data.ratio,
      height: 175 * this.data.ratio,
      //maskColor:'#dddddd',
      //size:15,
      //scale:1,
      scale: .9,
    })

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // console.log('触发了分享')
    // activityType: options.activityType,
    //   gameConfigName: options.gameConfigName
    return {
      title: this.data.detailData && this.data.detailData.shareTitle,
      imageUrl: 'https://oss.kiscloud.net/wechat/images/share1.jpg',
      path: `pages/games/scratchCard/index?activityType=${this.data.activityType}&gameConfigName=${this.data.gameConfigName}&shareMemberId=${this.data.memberId}&id=${this.data.activityId}&activityId=${this.data.activityId}&isShare=1`
    }
  }
})